package org.feng.support.proxy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.feng.base.entity.Result;
import org.feng.entity.PubFile;
import org.feng.entity.result.UploadResult;
import org.feng.service.IPubFileService;
import org.feng.utils.UploadFileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author : FengShuai
 * @since : 2024/7/8 13:47
 */
public class ProxyUpload {
    /**
     * 上传文件前检测文件是否已存在
     *
     * @param file 文件流
     * @return 上传结果
     * 不管是否存在，都返回fileMd5
     */
    public static UploadResult checkMd5(MultipartFile file) {
        String fileMd5 = null;
        try {
            fileMd5 = UploadFileUtils.getFileMd5(file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        IPubFileService sysFileService = SpringUtil.getBean(IPubFileService.class);
        PubFile dataFile = sysFileService.getOne(Wrappers.<PubFile>lambdaQuery().eq(PubFile::getMd5, fileMd5));
        UploadResult uploadResult = new UploadResult();
        if (dataFile != null) {
            uploadResult.setFileUrl(dataFile.getFilePath());
            uploadResult.setFileName(dataFile.getFileName());
            uploadResult.setFileSize(dataFile.getFileSize());
            uploadResult.setFileType(dataFile.getFileType());
        }
        uploadResult.setFileMd5(fileMd5);
        return uploadResult;
    }

    /**
     * 文件不存在时保存
     *
     * @param uploadResult 上传文件结果
     */
    public static void saveMd5(UploadResult uploadResult) {
        PubFile pubFile = new PubFile();
        pubFile.setFileName(uploadResult.getFileName());
        pubFile.setFileSize(uploadResult.getFileSize());
        pubFile.setFileType(uploadResult.getFileType());
        pubFile.setFilePath(uploadResult.getFileUrl());
        pubFile.setFilePath(uploadResult.getFileUrl());
        pubFile.setUploadTime(LocalDateTime.now());
        pubFile.setMd5(uploadResult.getFileMd5());
        IPubFileService sysFileService = SpringUtil.getBean(IPubFileService.class);
        sysFileService.save(pubFile);
    }
}
